package plugin_splicing

import (
	"log"
	"os"
	"os/exec"
	"time"
)

type SplicingTask struct {
	plugin       *SplicingConfig
	streamConfig StreamConfig
	cmd          *exec.Cmd

	p *SplicingPublisher
	s *SplicingSubscriber
}

// 重点方案，增加ffmpeg 进程异常退出重启功能  默认方法
// 学习stream 码流订阅用法
// 学习stream 码流发布用法
func (t *SplicingTask) setupFfmpegTransformThrd0() {
	SplicingPlugin.Info("setupFfmpegTransformThrd0 pipe in and out...")

	//添加一个循环 避免ffmpeg 进程异常退出，退出后自动重新启动
	for {
		t.status = 0

		//ffmpeg 启动次数+1
		t.restartFFCount++

		cmd := exec.Command(conf.Ffmpeg, "-re",
			"-i", "pipe:0",
			"-tune", "zerolatency", //编码延迟参数
			//"-vcodec", t.videoCodec,
			//"-g", "12", "-keyint_min", "12", //设置GOP 大小和关键帧间隔
			//"-b:v", "400k",
			//"-preset", "superfast", //编码延迟参数，superfast ultrafast  影响图像质量
			"-s", t.streamConfig.Resolution,
			"-r", t.streamConfig.Fps,
			"-vf",
			osdText,
			"-c:v", t.streamConfig.VideoCodec,
			//"drawtext=fontsize=100:fontfile=shoujin.ttf:text='m7s转码 ts2':x=500:y=500:fontcolor=green:box=1:boxcolor=yellow",
			//"-acodec", "libfaac",
			//"-b:a", "64k",
			"-acodec", "copy",
			"-f",
			"mpegts", //TS
			"pipe:1",
		)

		SplicingPlugin.Info(cmd.String())

		// Start the command
		err := cmd.Start()
		if err != nil {
			SplicingPlugin.Error("Error starting command:", zap.Error(err))
			continue
		}

		//定义一个订阅者
		s := &SplicingSubscriber{}
		//s.IsInternal = true
		s.task = t
		t.s = s

		if err := SplicingPlugin.Subscribe(t.streamConfig.StreamPath, s); err != nil {
			SplicingPlugin.Error("TransformPlugin 2 Subscribe faild")
			continue
		} else {
			//重点需要goroutin  启动订阅流，且只订阅了video track 裸流
			//避免重复请求播放
			if !s.IsPlaying() {
				SplicingPlugin.Info("TransformPlugin Subscribe sucess 2 play")
				go s.PlayRaw()
			}
		}

		SplicingPlugin.Info("cmd Start  wait end....\n")
		err = cmd.Wait()
		if err != nil {
			SplicingPlugin.Error("Error Wait command:", zap.Error(err))
		}

		//关闭订阅流
		if t.s != nil {
			SplicingPlugin.Info("try to close TransformSubscriber")
			t.s.Delete()
			t.s = nil
		}
		//关闭发布流
		if t.p != nil {
			t.p.Delete()
			t.p = nil
			SplicingPlugin.Info("try to close TransformPublisher")
		}
		SplicingPlugin.Info("ffmpegTransformThrd end to restart", zap.Int("restartFFCount", t.restartFFCount))

		//延迟后重启
		time.Sleep(time.Duration(1000) * time.Millisecond)

	}

}

func (t *SplicingTask) writeToFFPipe0(f *os.File, buf []byte) {
	_, err := f.Write(buf)
	if err != nil {
		SplicingPlugin.Error("splicing task write to pipe failed", zap.Error(err))
	}
}
